package mymyoux.io.sockets.servers.mserverClasses
{
	import mymyoux.io.sockets.mapping.Telegramme;
	import mymyoux.io.sockets.servers.mserverClasses.People;

	public class Room
	{
		private var _name:String;
		private var _peoples:Vector.<People>;
		private var _ids:Vector.<uint>;
		private var _telegrammeLogIn:Telegramme;
		private var _telegrammeLogOut:Telegramme;
		public function Room()
		{
			_peoples = new Vector.<People>();
			_ids = new Vector.<uint>();
			_telegrammeLogIn = new Telegramme();
			_telegrammeLogIn.command = Telegramme.LOG_IN_ROOM;
			_telegrammeLogOut = new Telegramme();
			_telegrammeLogOut.command = Telegramme.LOG_OUT_ROOM;
			
		}
		public function get empty():Boolean
		{
			return _ids.length > 0;
		}
		public function get name():String
		{
			return _name;
		}

		public function set name(value:String):void
		{
			_name = value;
			_telegrammeLogIn.room = _name;
			_telegrammeLogOut.room = _name;
		}
		public function get peoplesId():Vector.<uint>
		{
			return _ids;
		}
		public function contains(people:People):Boolean
		{
			return _ids.indexOf(people.id) > -1;
		}
		public function add(people:People):void
		{
			if(!contains(people))
			{
				var p:String;
				_telegrammeLogIn.id = people.id;
				for(p in _peoples)
				{
					_peoples[p].socket.write(_telegrammeLogIn);	
				}
				_peoples.push(people);
				_ids.push(people.id);
				people.addRoom(_name);
				people.signalRoomData.add(_name, onPeopledata, people);
			}
		}
		private function onPeopledata(telegramme:Telegramme, people:People):void
		{
			var p:String;
			telegramme.id = people.id;
			for(p in _peoples)
			{
				_peoples[p].socket.write(telegramme);	
			}
		}
		public function rem(people:People):void
		{
			var index:int = _ids.indexOf(people.id);
			if(index > -1)
			{
				var p:String;
				_telegrammeLogOut.id = people.id;
				for(p in _peoples)
				{
					_peoples[p].socket.write(_telegrammeLogOut);	
				}
				_peoples[index].signalRoomData.remove(_name, onPeopledata);
				_peoples.splice(index, 1);
				_ids.splice(index, 1);
				people.remRoom(_name);
			}
		}
	}
}